import React, {Component} from 'react';
import './index.css';
import Config from '../../config';
import Ajax from '../ajax';
import {Button, Modal, Table, Icon, Select, Input, message} from 'antd';
import Util from '../../common/util';

const {Column} = Table;
const Option = Select.Option;

class LinkWhere extends Component {

    static defaultProps = {
        defaultLinkData: null,
        defaultLinkType: '',

        onSelected: () => {
        },
    };


    constructor(props) {
        super(props);

        this.state = {
            visible: false,

            goodsList: [],
            totalGoodsNum: 0,
            articleList: [],
            totalArticleNum: 0,
            pageList: [],
            actList: [
                {
                    uid: Util.getUId(),
                    name: '砍价',
                    ty: 1
                },
                {
                    uid: Util.getUId(),
                    name: '秒杀',
                    ty: 2
                },
                {
                    uid: Util.getUId(),
                    name: '团购',
                    ty: 3
                }
            ],

            linkType: props.defaultLinkType,
            linkData: props.defaultLinkData,
        };

        this._selectType = 'goods';

    }

    render() {
        var _self = this;
        var selectType = this._selectType;
        var {visible, linkType, linkData} = this.state;
        var modalTitle = '';

        if (selectType == 'goods') {
            modalTitle = '选择商品';
        } else if (selectType == 'article') {
            modalTitle = '选择文章';
        } else if (selectType == 'page') {
            modalTitle = '选择页面';
        } else if (selectType == 'act') {
            modalTitle = '营销活动';
        } else if (selectType == 'goodsCate') {
            modalTitle = '商品分类';
        } else if (selectType == 'phone') {
            modalTitle = '电话号码';
        }


        return (
            <div className="linkWhere">
                <Select
                    defaultValue={linkType}
                    style={{width: 120}}
                    onSelect={this._selectLink.bind(this)}
                >
                    <Option value="">请选择</Option>
                    <Option value="goods">商品</Option>
                    <Option value="article">文章</Option>
                    <Option value="page">页面</Option>
                    <Option value="goodsCate">商品分类</Option>
                    <Option value="phone">电话号码</Option>
                    {/*<Option value="act">营销活动</Option>*/}
                </Select>

                {
                    _self._rendLinkData()
                }

                <Modal
                    visible={visible}
                    title={modalTitle}
                    footer={null}
                    width={700}
                    onCancel={() => {
                        this.setState({
                            visible: false,
                        });
                    }}
                >
                    {
                        _self._rendList(selectType)
                    }
                </Modal>
            </div>
        );
    }

    _rendLinkData() {
        var {visible, linkType, linkData} = this.state;

        if (!linkData) {
            return null;
        }

        if (linkType == 'goods') {
            return (
                <div className="selGoods">
                    <div className="selGoods__img"
                         style={{backgroundImage: 'url(' + linkData.image_url + ')'}}
                    />
                    <div className="selGoods__info">
                        <div className="selGoods__name">{linkData.name}</div>
                        <div className="selGoods__price">￥{linkData.sale_price}</div>
                    </div>
                    <div onClick={this._delItem.bind(this)} className="selGoods__del"></div>
                </div>
            )
        } else if (linkType == 'article') {
            return (
                <div className="selGoods">
                    <div className="selGoods__img"
                         style={{backgroundImage: 'url(' + linkData.image_url + ')'}}
                    />
                    <div className="selGoods__info">
                        <div className="selGoods__name">{linkData.title}</div>
                        <div className="selGoods__time">{linkData.create_time}</div>
                    </div>
                    <div onClick={this._delItem.bind(this)} className="selGoods__del"></div>
                </div>
            )
        } else if (linkType == 'page') {
            return (
                <div className="selGoods">
                    <div className="selGoods__info">
                        <div className="selGoods__name">页面名称：<b>{linkData.name}</b></div>
                    </div>
                    <div onClick={this._delItem.bind(this)} className="selGoods__del"></div>
                </div>
            )
        } else if (linkType == 'act') {
            return (
                <div className="selGoods">
                    <div className="selGoods__info">
                        <div className="selGoods__name">活动名称：<b>{linkData.name}</b></div>
                    </div>
                    <div onClick={this._delItem.bind(this)} className="selGoods__del"></div>
                </div>
            )
        } else if (linkType == 'goodsCate') {
            return (
                <div className="selGoods">
                    <div className="selGoods__info">
                        <div className="selGoods__name">商品分类 名称：<b>{linkData.name}</b></div>
                    </div>
                    <div onClick={this._delItem.bind(this)} className="selGoods__del"></div>
                </div>
            )
        } else if (linkType == 'phone') {
            return (
                <div className="selGoods">
                    <div className="selGoods__info">
                        <div className="selGoods__name">电话号码：<b>{linkData.phone}</b></div>
                    </div>
                    <div onClick={this._delItem.bind(this)} className="selGoods__del"></div>
                </div>
            )
        }
    }

    _rendList(selectType) {
        var _self = this
        var {goodsList, articleList, totalGoodsNum, totalArticleNum, pageList, actList, cateList} = _self.state

        if (selectType == 'goods') {
            return _self._rendGoods(goodsList, totalGoodsNum)
        } else if (selectType == 'article') {
            return _self._rendArticle(articleList, totalArticleNum)
        } else if (selectType == 'page') {
            return _self._rendPage(pageList)
        } else if (selectType == 'act') {
            return _self._rendActList(actList)
        } else if (selectType == 'goodsCate') {
            return _self._rendCateList(cateList);
        } else if (selectType == 'phone') {
            return _self._rendPhoneContent();
        }
    }

    _rendGoods(goodsList, totalGoodsNum) {
        var _self = this;

        return (
            <Table
                dataSource={goodsList}
                rowKey={record => record.id}
                scroll={{y: 400}}
                pagination={
                    {
                        defaultCurrent: 1,
                        defaultPageSize: 10,
                        total: totalGoodsNum,
                        onChange: (page, pageSize) => {
                            _self._selectGoods(page);
                        }
                    }
                }
            >
                <Column
                    title="商品主图"
                    dataIndex="image_url"
                    key="image_url"
                    render={imageUrl => (<img className="tableCell__img" src={imageUrl} alt=""/>)}
                />
                <Column
                    title="商品名"
                    dataIndex="name"
                    key="name"
                />
                <Column
                    title="销售价"
                    dataIndex="sale_price"
                    key="sale_price"
                />
                <Column
                    title="操作"
                    key="action"
                    render={(text, goods) => {
                        return (
                            <Button type="primary" onClick={() => {
                                _self._selectOk(goods);
                            }}>选择</Button>
                        )
                    }}
                />
            </Table>
        )
    }

    _rendArticle(articleList, totalArticleNum) {
        var _self = this;
        return (
            <Table
                dataSource={articleList}
                rowKey={record => record.id}
                scroll={{y: 400}}
                pagination={
                    {
                        defaultCurrent: 1,
                        defaultPageSize: 10,
                        total: totalArticleNum,
                        onChange: (page, pageSize) => {
                            _self._selectArticle(page);
                        }
                    }
                }
            >
                <Column
                    title="文章标题"
                    dataIndex="title"
                    key="title"
                />
                <Column
                    title="文章主图"
                    dataIndex="image_url"
                    key="image_url"
                    render={imageUrl => (<img className="tableCell__img" src={imageUrl} alt=""/>)}
                />
                <Column
                    title="创建时间"
                    dataIndex="create_time"
                    key="create_time"
                />
                <Column
                    title="操作"
                    key="action"
                    render={(text, article) => {
                        return (
                            <Button type="primary" onClick={() => {
                                var art = JSON.parse(JSON.stringify(article));
                                delete art.content;
                                _self._selectOk(art);
                            }}>选择</Button>
                        )
                    }}
                />
            </Table>
        )
    }

    _rendPage(pageList) {
        var _self = this;

        return (
            <Table
                dataSource={pageList}
                rowKey={record => record.id}
                scroll={{y: 400}}
                pagination={false}
            >
                <Column
                    title="页面名称"
                    dataIndex="name"
                    key="name"
                />
                <Column
                    title="操作"
                    key="action"
                    render={(text, item) => {
                        return (
                            <div className="table__btnsWrap">
                                <Button type="primary" onClick={() => {
                                    _self._selectOk(item);
                                }}>选择</Button>
                            </div>
                        )
                    }}
                />
            </Table>
        )
    }

    _rendActList(actList) {
        var _self = this;

        return (
            <Table
                dataSource={actList}
                rowKey={record => record.uid}
                scroll={{y: 400}}
                pagination={false}
            >
                <Column
                    title="活动"
                    dataIndex="name"
                    key="name"
                />
                <Column
                    title="操作"
                    key="action"
                    render={(text, item) => {
                        return (
                            <div className="table__btnsWrap">
                                <Button type="primary" onClick={() => {
                                    _self._selectOk(item);
                                }}>选择</Button>
                            </div>
                        )
                    }}
                />
            </Table>
        )
    }

    _rendCateList(cateList) {
        var _self = this;

        return (
            <Table
                dataSource={cateList}
                rowKey={record => record.category_id}
                scroll={{y: 400}}
                pagination={false}
            >
                <Column
                    title="分类名称"
                    dataIndex="name"
                    key="name"
                />
                <Column
                    title="操作"
                    key="action"
                    render={(text, item) => {
                        return (
                            <div className="table__btnsWrap">
                                <Button type="primary" onClick={() => {
                                    _self._selectOk(item);
                                }}>选择</Button>
                            </div>
                        )
                    }}
                />
            </Table>
        )
    }

    _rendPhoneContent() {
        var _self = this;
        var {linkData} = this.state;

        return (
            <div className="phoneContent">
                {/*<div className="phoneContent__title">电话号码</div>*/}
                <Input
                    placeholder="请输入电话号码"
                    defaultValue={linkData ? linkData.phone : ''}
                    onInput={
                        (e) => {
                            this._callphone = e.target.value;
                        }
                    }
                    className="phoneContent__input"
                />
                <div className="phoneContent__btns">
                    <Button
                        onClick={() => {
                            this.setState({
                                visible: false
                            });
                        }}
                        type="default"
                        className="btnCancel"
                    >取消</Button>
                    <Button
                        onClick={() => {
                            if (!this._callphone) {
                                message.warning('请输入电话号码');
                                return;
                            }
                            if (!/^1[\d]{10}$/.test(this._callphone)) {
                                message.warning('电话号码格式不正确');
                                return;
                            }
                            _self._selectOk({
                                phone: this._callphone
                            });
                        }}
                        type="primary"
                    >确定</Button>
                </div>
            </div>
        );

    }

    _selectLink(ty) {
        if (!ty) {
            return;
        }
        if (ty == 'phone' && Config.global.tmplId < 310) {
            message.warn(Config.tips.tmplIdLow);
            return;
        }

        this._selectType = ty;

        this.setState({
            visible: true,
        });

        if (ty == 'goods') { //链接到商品
            this._selectGoods(1);
        } else if (ty == 'article') { //链接到文章
            this._selectArticle(1);
        } else if (ty == 'page') { //链接到页面
            this._selectPage();
        } else if (ty == 'act') {
            this._selectAct();
        } else if (ty == 'goodsCate') { //连接到商品分类
            this._selectGoodsCate();
        } else if (ty == 'phone') {
            this._selectPhone();
        }
    }

    _selectGoods(page) {
        var _self = this;

        page = page || 1;

        Ajax.G('/admin/Goods/getGoodsList', {page: page}, function (res) {
            var data = res['result'];

            _self.setState({
                goodsList: data.goodsList,
                totalGoodsNum: parseInt(data.totalNum)
            });
        });
    }

    _selectArticle(page) {
        var _self = this;

        page = page || 1;

        Ajax.G('/admin/Article/getArticleList', {page: page}, function (res) {
            var data = res['result'];

            _self.setState({
                articleList: data.articleList,
                totalArticleNum: parseInt(data.totalNum)
            });

        });
    }

    _selectPage() {
        var _self = this;

        Ajax.G('/admin/Home/getPageList', {}, function (res) {
            var pageList = res.result.pageList;

            pageList = pageList.map(function (page) {
                return {
                    name: page.page_type == 0 ? '首页' : page.page_name,
                    type: page.page_type,
                    state: page.state,
                    id: page.id,
                }
            })

            _self.setState({
                pageList
            });
        });
    }

    _selectAct() {
    }

    /**
     * 链接到商品分类
     * @private
     */
    _selectGoodsCate() {
        var _self = this;

        Ajax.G('/api/Category/getCategory', {
            type: 0
        }, function (res) {
            var cateList = res.result.catList;

            _self.setState({
                cateList
            });
        });
    }

    /**
     * 链接到电话号码
     * @private
     */
    _selectPhone() {

    }

    _selectOk(item) {
        var _self = this;
        var selectType = this._selectType;

        _self.setState({
            visible: false,
            linkType: selectType,
            linkData: item,
        });

        this.props.onSelected && this.props.onSelected(item, selectType);
    }

    _delItem() {
        this._selectOk(null);
    }
}

export default LinkWhere;
